<?php

    class News_Controller extends Application {
        
        function setup()
        {
            $this->actions = array('index','category','read','archives','preview');
            $this->before_filter('is_logged_in',array('only'=>'preview'));
            use_model('news','news_categories');
        }
        
		function index() 
		{
		    // list most recent articles, 10 per pages
		    $news = new News();
		    $this->assign('articles_pager',$news->recent_stories_paged());
		    $this->assign('is_logged_in',$this->can_edit());
		}

        function archives()
		{
		    $news = new News();
		    // show all archives
		    if ( empty($this->params['year']) &&  empty($this->params['month']))
		    {
		        $this->assign('archives_list',$news->archives_list());
		    } else {
		        // int the year and month
		        $year  = (int) $this->params['year'];
		        $month = (int) $this->params['month'];	
		        $mdate  = get_month($month);
		        $this->assign('archive_date', "$mdate $year");	        
		        
		        // if less than 0 or > 12, set to current month
		        if ( $month <= 0 || $month > 12 )
		        {
		            $month = date('m');
		        } else {
		            $month = sprintf("%02d",$month);
		        }
		        $this->assign('articles_pager',$news->browse_by_date($year,$month));
		    } 
		}

		function category() 
		{
		    // get news by category
		    $category = $this->params['id'];
		    
		    if ( empty($category) )
		    {
		        $this->redirect_to('index');
		    }
		    
		    $news = new News();
		    $this->assign('is_logged_in',$this->can_edit());
		    $this->assign('articles_pager',$news->get_stories_by_category($category));
		}


		function read() 
		{
		    $index_name = $this->params['id'];
		    $news = new News();
		    $this->assign_ref('news', $news);
		    if ( $news->load_by_index_name($index_name,false) )
		    {
		        $this->assign('is_logged_in',false);
		    } else {
		        $this->error_404();
		        return;
		    }
		}

        function can_edit()
        {
            if(!empty($_SESSION['user_id'])){    
               return true;
            }
        }
        
        function preview()
        {
            $index_name = $this->params['id'];
		    $news = new News();
		    $this->assign_ref('news', $news);
		    if ( $news->load_by_index_name($index_name,false) )
		    {
		        $this->assign('is_logged_in',false);		        
    		    $this->render(array('template'=>'read.php'));
		    } else {
		        $this->error_404();
		        return;
		    }		    
        }
        
    }

?>